package com.citycloud.datac.client.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citycloud.datac.client.cache.CacheManager;
import com.citycloud.datac.client.cache.ehcache.EhCacheManager;
import com.citycloud.datac.client.client.DataCOauth2Client;
import com.citycloud.datac.client.dto.ResourceServerConfigurer;
import com.citycloud.datac.client.properties.SecurityConfigurter;
import com.citycloud.datac.client.token.RemoteTokenServices;
import com.citycloud.datac.client.token.ResourceServerTokenServices;

public class DataCOAuth2ClientConfigurerAdapter implements DataCOAuth2ClientConfigurer {
	private static Logger log = LoggerFactory.getLogger(DataCOAuth2ClientConfigurerAdapter.class);

	final SecurityConfigurter.SecurityClientConfig clientConfig;
	final SecurityConfigurter.SecurityResourceConfig resourceConfig;
	/**缺省的缓存*/
	private CacheManager cacheManager;
	private ResourceServerTokenServices tokenService;

	public DataCOAuth2ClientConfigurerAdapter(final SecurityConfigurter.SecurityClientConfig clientConfig,
			final SecurityConfigurter.SecurityResourceConfig resourceConfig) {
		this.clientConfig = clientConfig;
		this.resourceConfig = resourceConfig;
	}

	@Override
	public void configure(ResourceServerConfigurer resourceServerConfigurer) {
		log.info("初始化dataCOAuth2Client缓存,并测试是否正常工作");
		if (resourceServerConfigurer.getResourceTokenServices() != null) {
			this.tokenService = resourceServerConfigurer.getResourceTokenServices();
		} else {
			this.tokenService = new RemoteTokenServices(clientConfig, resourceConfig);
		}
		if (resourceServerConfigurer.getCacheManager() != null) {
			this.cacheManager = resourceServerConfigurer.getCacheManager();
		} else {
			this.cacheManager = new EhCacheManager();
		}
		log.info("初始化dataCOAuth2Client缓存完成");

	}

	@Override
	public DataCOauth2Client getOauth2Client() {
		DataCOauth2Client client = new DataCOauth2Client();
		client.setCacheManager(cacheManager);
		client.setTokenService(tokenService);
		return client;

	}
}
